package com.iakuil.app.common.db.handler;

import com.iakuil.app.common.core.util.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.lang.reflect.Array;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Java 数组/集合与数据库VARCHAR类型转换器抽象类
 *
 * <p>数据库字段值是以半角逗号分隔的字符串，e.g. 1001，1002，1003
 * <p>注意：如果是MyBatis Plus，{@link com.baomidou.mybatisplus.annotation.TableName}注解需要开启<strong>autoResultMap = true</strong>
 *
 * @author Kai
 * @date 2022/1/26 0:06
 **/
public abstract class StringTokenizerTypeHandler<T> extends BaseTypeHandler<T[]> {
    private final Class<T> clazz;

    public StringTokenizerTypeHandler(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T[] ts, JdbcType jdbcType) throws SQLException {
        ps.setString(i, StringUtils.join(ts, ","));
    }

    @Override
    public T[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        return toArray(resultSet.getString(columnName));
    }

    @Override
    public T[] getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return toArray(resultSet.getString(columnIndex));
    }

    @Override
    public T[] getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        return toArray(callableStatement.getString(columnIndex));
    }

    T[] toArray(String columnValue) {
        if (columnValue == null || columnValue.isEmpty()) {
            return createArray(0);
        }
        String[] values = columnValue.split(",");
        T[] array = createArray(values.length);
        for (int i = 0; i < values.length; i++) {
            array[i] = parseString(values[i]);
        }
        return array;
    }

    @SuppressWarnings("unchecked")
    T[] createArray(int size) {
        return (T[]) Array.newInstance(clazz, size);
    }

    /**
     * 将字符串值解析成期望的对象
     *
     * @param value 字符串值
     * @return 解析后的对象
     */
    abstract T parseString(String value);
}
